package com.gxy.learn.securityauth.jwt;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Description(jwt验证token辅助)
 * author: Gao xueyong
 * Create at: 2022/1/4 下午10:53
 */
@Slf4j
@Component
public class JwtVersionUtil {

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Autowired
    CacheManager cacheManager;

    /**
     * 刷新登录版本号
     *
     * @param userName
     * @return
     */
    public Integer refreshLoginVersion(String userName) {
        Cache cache = cacheManager.getCache(JwtUtil.CAPTCHA_CACHE_KEY);
        String loginVersionKey = JwtUtil.loginVersionKey(userName);
        Integer loginVersion = loginVersion(userName);
        Integer newLoginVersion = loginVersion + JwtUtil.CLAIM_KEY_LOGIN_VERSION_VAL;
        log.info("当前登录人[{}]在[{}]登录版本号由[{}]变更为[{}]", userName, sdf.format(new Date()), loginVersion, newLoginVersion);
        // 登录版本号，登录时默认设置为1 登出后版本号+1
        cache.put(loginVersionKey, newLoginVersion);
        return newLoginVersion;
    }


    /**
     * 获取版本号
     *
     * @param userName
     * @return
     */
    public Integer loginVersion(String userName) {
        Cache cache = cacheManager.getCache(JwtUtil.CAPTCHA_CACHE_KEY);
        String loginVersionKey = JwtUtil.loginVersionKey(userName);
        Integer loginVersion = cache.get(loginVersionKey, Integer.class);
        return null == loginVersion ? JwtUtil.CLAIM_KEY_LOGIN_VERSION_VAL : loginVersion;
    }


}
